package com.jun.flower.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jun.flower.bean.TbBuycar;
import com.jun.flower.bean.TbFlowers;
import com.jun.flower.bean.TbUser;
import com.jun.flower.service.BuyCarService;
import com.jun.flower.service.FlowerService;
import com.jun.flower.service.UserService;

@Controller
public class BuyCarController {
	@Autowired
	private BuyCarService buycarService;
	@Autowired
	protected FlowerService flowerService;
	@Autowired
	protected UserService userService;
	
	@RequestMapping("/buy/car")
	public String addBuyCar(Model model,Integer flowersId, Integer userId) {
		if(buycarService.checkBuyCar(flowersId, userId)) {
		model.addAttribute("userId", userId);
		buycarService.addBuyCar(flowersId, userId);
		return "web-carsuccess";
		}else {
			return "web-carexist";
		}
		
	}
	
	@RequestMapping("/show/car")
	public String showBuyCar(Model model,Integer userId) {
		List<TbBuycar> list = buycarService.showBuyCar(userId);
		List<TbFlowers> flowerlist = new ArrayList<>();
		for(int i=0;i<list.size();i++) {
			Integer flowerId = list.get(i).getFlowersId();
			TbFlowers flower = flowerService.getFlowerById(flowerId);
			flowerlist.add(flower);
		}
		model.addAttribute("flowerlist", flowerlist);
		
		TbUser user = userService.getUserById(userId);
		model.addAttribute("user", user);
		//用来删除
		model.addAttribute("userId",userId);
		return "web-car";
	}
	
	
	@RequestMapping("/delete/car")
	public String deleteBuyCar(Model model,Integer flowersId,Integer userId) {
		buycarService.deleteBuyCar(flowersId, userId);
		return "redirect:/show/car?userId="+userId;
	}
	
	@RequestMapping("/next/car")
	@ResponseBody
	public Map nextCar(String ids) {
		Map data = new HashMap<>();
		if(ids != null && !ids.isEmpty()) {
			String[] arrStr = ids.split("\\,");
			List<Integer> list = new ArrayList<>();
			for(int i=0;i<arrStr.length;i++) {
				list.add(Integer.parseInt(arrStr[i]));	
			}
			List<TbFlowers> listFlower = new ArrayList<>();
			for(Integer i : list) {
				TbFlowers flower= flowerService.getFlowerById(i);
				listFlower.add(flower);
			}
			data.put("listFlower", listFlower);
			data.put("state", true);
		}else {
			data.put("state", false);
		}
		return data;
	}
	
}
